package com.huatai.datadevelop.service;

import com.alibaba.fastjson.JSON;
import com.huatai.datadevelop.constant.RedisConstant;
import com.huatai.datadevelop.entity.RealApiVonversionEntity;
import com.huatai.datadevelop.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
//import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@Service
public class RealCommonService {
	@Autowired
	private RedissonClient redissonClient;
    ///private ReentrantLock lock = new ReentrantLock();

    /**
     * 值替换
     * 原始数据先转化
     *
     * @param realApiVonversionEntityList
     * @param fetchData
     * @return
     */
    public Object getDataConversionMapOtList(List<RealApiVonversionEntity> realApiVonversionEntityList, Object fetchData) {
        //值是列表
        if (fetchData instanceof ArrayList) {
            List<HashMap> hashMapList = JSON.parseArray(JSON.toJSONString(fetchData), HashMap.class);
            if (hashMapList != null && hashMapList.size() > 0) {
                hashMapList.parallelStream().forEachOrdered(hashMap -> {
                    this.getDataConversion(realApiVonversionEntityList,hashMap);
                });
            }
            return hashMapList;
        } else {
            HashMap hashMap = JSON.parseObject(JSON.toJSONString(fetchData), HashMap.class);
            this.getDataConversion(realApiVonversionEntityList,hashMap);
            return hashMap;
        }
    }

    /**
     * 值替换
     *
     * @param realApiVonversionEntityList
     * @param fetchData
     * @return
     */
    private void getDataConversion(List<RealApiVonversionEntity> realApiVonversionEntityList, HashMap<String, Object> fetchData) {
		RLock lock = redissonClient.getLock(RedisConstant.PERMISSION_LOCK);
		lock.lock();
        try {
            for (HashMap.Entry<String, Object> map : fetchData.entrySet()) {
                List<RealApiVonversionEntity> collect = realApiVonversionEntityList.stream().filter(p -> p.getKeyName().equalsIgnoreCase(map.getKey())).collect(Collectors.toList());
                collect.stream().forEach(entity -> {
                    Object param = "";
                    switch (entity.getType()) {
                        //值替换
                        case "值替换":
                            param = map.getValue()!=null?this.valueConversion(entity,map.getValue().toString()):map.getValue();
                            break;
                        //字段脱敏
                        case "字段脱敏":
                            param = map.getValue()!=null?this.fieldDesensitization(map.getValue().toString(),entity.getRegix(),entity.getTarget()):map.getValue();
                            break;
                        //时间戳转换
                        case "时间戳转换":
                            param = map.getValue()!=null?this.timestampConversion(map.getValue().toString(),entity.getValue()):map.getValue();
                            break;
                        //时间转换
                        case "时间转换":
                            param = map.getValue()!=null?this.timeConversion(map.getValue().toString()):map.getValue();
                            break;
                    }
                    map.setValue(param);
                });
            }
        } catch (Exception ex) {
            System.out.println("值替换报错：" + ex.getMessage());
        } finally {
            lock.unlock();
        }
    }

    /**
     * 值替换
     *
     * @return
     */
    public String valueConversion(RealApiVonversionEntity entity, String source) {
        if (entity.getTitle().equalsIgnoreCase(source)) {
            source = entity.getValue();
        }
        return source;
    }

    /**
     * 字段脱敏
     * @param source 原始数据
     * @param regex  脱敏规则
     * @return
     */
    public String fieldDesensitization(String source,String regex,String target) {
        if(StringUtils.isEmpty(source)){
            return source;
        }
        try{
            return source.replaceAll(regex,target);
        }catch (Exception ex){
            return source;
        }
    }

    /**
     * 时间戳转换
     *
     * @return
     */
    public String timestampConversion(String source,String temp) {
        return DateUtils.getTimeInMillisHDM(source,temp);
    }

    /**
     * 时间转换
     *
     * @return
     */
    public String timeConversion(String source) {
        //替换2022-01-01T00:00:00.000 为 2020-01-01 00:00:00
        if (source.contains(".")) {
            String[] split = source.split("\\.");
            source = split[0];
        }

        //替换2022-01-01T00:00:00 为 2020-01-01 00:00:00
        if (source.contains("T")) {
            source = source.replace("T", " ");
        }

        //替换2022/01/01 00:00:00 为 2020-01-01 00:00:00
        if (source.contains("/")) {
            source = source.replaceAll("/", "-");
        }
        return source;
    }
}
